import Vue from 'vue';
import Router from 'vue-router';
import extendRouter from './module/index';
import { setCookieTenant } from '@/lib/auth';

Vue.use(Router);
const router = new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: extendRouter
});

// 路由跳转检测
router.beforeEach((to, from, next) => {
  if (to.path === '/') {
    // 处理
    let returnUrlData = '';
    if (to.query && to.query.ReturnUrl) {
      returnUrlData = decodeURIComponent(
        decodeURIComponent(to.query.ReturnUrl)
      ).split('&');
    }
    let tenantId = '';
    for (const i in returnUrlData) {
      if (/^acr_values=/.test(returnUrlData[i])) {
        tenantId = returnUrlData[i].replace('acr_values=', '');
        break;
      }
    }
    tenantId = tenantId ? window.atob(tenantId) : '';
    tenantId =
      tenantId && tenantId.split('___').length > 0
        ? tenantId.split('___')[0]
        : '';
    tenantId = tenantId === '%2C' ? '' : tenantId;
    console.log('routerbefore--tenantId', tenantId);
    setCookieTenant(tenantId);
    next({ ...to, ...{ path: '/login/l__' + tenantId }, replace: true });
  } else {
    next();
  }
});

export default router;
